<template>
  <!-- 导航栏 -->
  <CustomNavbar></CustomNavbar>
  <scroll-view
    class="scroll-view"
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrollTolower"
    scroll-y
  >
    <!-- 骨架屏 -->
    <PageSkeleton v-if="isLoading"></PageSkeleton>
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="BannerList"></XtxSwiper>
      <!-- 分类列表 -->
      <CategoryPanel :list="HomeCategory"></CategoryPanel>
      <!-- 热门推荐 -->
      <HotPanel :list="HomeHot"></HotPanel>
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef"></XtxGuess>
    </template>
  </scroll-view>
</template>

<script setup lang="ts">
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import { ref } from 'vue'
import type { XtxGuessInstance } from '@/types/component'
import { useGuessList } from '@/composables/index'

const BannerList = ref<BannerItem[]>([])
const HomeCategory = ref<CategoryItem[]>([])
const HomeHot = ref<HotItem[]>([])
// 获取轮播图数据
const getHomeBanner = async () => {
  const res = await getHomeBannerAPI()
  BannerList.value = res.result
}
// 获取前台分类数据
const getHomeCategory = async () => {
  const res = await getHomeCategoryAPI()
  HomeCategory.value = res.result
}
// 获取热门推荐数据
const getHomeHot = async () => {
  const res = await getHomeHotAPI()
  HomeHot.value = res.result
}
// 猜你喜欢组合式函数
const { guessRef, onScrollTolower } = useGuessList()

// 下拉刷新状态
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 这样会依次等待上一个请求发送完才会接着发送下一个请求，增加了等待时间，性能不好
  // await getHomeBanner()
  // await getHomeCategory()
  // await getHomeHot()
  // 重置页码数据
  guessRef.value?.resetData()
  // 等待所有请求发送完才执行下一行代码，同时发送请求
  await Promise.all([getHomeBanner(), getHomeCategory(), getHomeHot()])
  // 关闭动画
  isTriggered.value = false
  // 重置猜你喜欢数据
  guessRef.value?.guessMove()
}

const isLoading = ref(false)
// 页面首次加载
onLoad(async () => {
  isLoading.value = true
  Promise.all([getHomeBanner(), getHomeCategory(), getHomeHot()])
  isLoading.value = false
})
</script>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f7f7f7;
}
.scroll-view {
  flex: 1;
}
</style>
